using System;
using System.Web;
using System.Web.UI;
using System.Configuration;
using System.Text;
using System.IO;

namespace Subgurim.Controles.SSM
{
    /*
     * FUTURE 
     * - Use Response.Filters to set the HASH
     * - Apply Regex to rewriterRules, forbiddenUrls, etc.
     * - Does forbiddenUrls are working perfectly (test it)
     * 
     * 
     * - The robot doesn't work
     * - It needs a cache from more than 5 minutes
     * - Syncronize the robots.txt and ASP.NET rules with forbiddenUrls
     * - Add a new item "Visits" that, in any kind of way, helps with the priority
     * - A way to establish priorities in the XML
     * - The forbiddenPaths should work tih the already saved cache
     * 
     */
    public class SubgurimSiteMapContextRequest : IHttpModule
    {
        #region IHttpModule Members
        public void Init(HttpApplication application)
        {
            application.BeginRequest += new EventHandler(this.context_BeginRequest);
            //application.AddOnBeginRequestAsync(new BeginEventHandler(this.context_BeginRequest), null);
        }
        public void Dispose() { }
        #endregion

        //public IAsyncResult context_BeginRequest(Object sender, EventArgs args, AsyncCallback cb, Object state)
        private void context_BeginRequest(Object sender, EventArgs args)
        {
            HttpContext context = ((HttpApplication)sender).Context;

            SubgurimSiteMapConfiguration config
                = (SubgurimSiteMapConfiguration)ConfigurationManager.GetSection("SubgurimSiteMapConfiguration");

            Uri uri = context.Request.Url;

            if (SubgurimSiteMapUtilities.takeLocalPath() == config.sitemapResponse)
            {
                SubgurimSiteMapUtilities.showOnScreen(SubgurimSiteMapBLL.showSiteMap(), context.Response);
            }
            else if (!SubgurimSiteMapUtilities.IAmAutoCalling(context) && filter(config, ref uri))
            {
                //SubgurimSiteMapBLL.addSiteMap(uri.AbsoluteUri);
                
                if (File.Exists(context.Request.PhysicalPath))
                {
                    var schema = uri.Scheme; //NEW
                    var host = uri.Host; //NEW
                    var pathepag = context.Request.RawUrl; //NEW
                    var urlFixed = string.Format("{0}://{1}{2}", schema, host, pathepag); //NEW
                    if (uri.Port != 80)
                    {
                        var port = uri.Port;
                        urlFixed = string.Format("{0}://{1}:{2}{3}", schema, host, port, pathepag);
                    }


                    SubgurimSiteMapBLL.addSiteMap(urlFixed); //NEW
                }

            }
        }


        private bool filter(SubgurimSiteMapConfiguration config, ref Uri uri)
        {
            // If the extension is not accepted, return false
            bool extensiones = false;
            if (!config.acceptedExtensions.Contains(".aspx"))
                config.acceptedExtensions.Add(".aspx");

            foreach (string ext in config.acceptedExtensions)
            {
                if (SubgurimSiteMapUtilities.takeLocalPath().EndsWith(SubgurimSiteMapUtilities.fixToLocalPath(ext)))
                    extensiones = true;
            }
            if (!extensiones) return false;



            // If the path is forbidden, return false
            // If the path is forbidden, return false
            bool prohibido = false;
            foreach (string fp in config.forbiddenPaths)
            {
                if (SubgurimSiteMapUtilities.takeLocalPath().StartsWith(SubgurimSiteMapUtilities.fixToLocalPath(fp)))
                {
                    prohibido = true;
                    break;
                }
            }
            if (prohibido) return false;


            bool prohibido2 = false;
            foreach (string fp in config.forbiddenPaths)
            {
                if (SubgurimSiteMapUtilities.takeLocalRawUrl().StartsWith(SubgurimSiteMapUtilities.fixToLocalPath(fp)))
                {
                    prohibido = true;
                    break;
                }
            }
            if (prohibido2) return false;



            // Make changes on the url
            string newUri = uri.AbsoluteUri.ToLower();
            foreach (RewriterRule rul in config.rewriterRules)
            {
                newUri = newUri.Replace(rul.oldPath, rul.newPath);
            }

            if (newUri != uri.AbsoluteUri.ToLower())
            {
                uri = new Uri(newUri);
            }


            return true;
        }

    }

}